package com.hmall.gateway.filter;

import com.hmall.gateway.properties.AuthProperties;
import com.hmall.gateway.utils.JwtTool;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;


@Component
@Order(-1)
@Slf4j
@RequiredArgsConstructor
public class MyAuthGlobalFilter implements GlobalFilter {

    private final AuthProperties authProperties;
    private final JwtTool jwtTool;
    private AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        // 1.放行不拦截的资源
        String url = request.getPath().toString();
        if(isExclude(url)){
            return chain.filter(exchange);
        }
        // 2.校验JWT
        String token = request.getHeaders().getFirst("authorization");
        try {
            // 4.合法，放行，并设置请求头信息
            Long userId = jwtTool.parseToken(token);
            String userInfo = userId.toString();
            exchange.mutate()
                    .request(b -> b.header("user-info", userInfo))
                    .build();
        } catch (Exception e) {
            // 3.非法，拦截，响应401
            //throw new RuntimeException(e);
            log.error("JWT校验失败了:{}", e.getMessage());
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        return chain.filter(exchange);
    }

    /**
     * 校验是否是一个放行的URL
     * @param url 需要校验的URL
     * @return 是否通过
     */
    private boolean isExclude(String url) {
        List<String> excludePaths = authProperties.getExcludePaths();
        for (String excludePath : excludePaths) {
            if (antPathMatcher.match(excludePath, url)) {
                return true;
            }
        }
        return false;
    }
}
